﻿using System;
using System.Web;
using System.Web.Services;
using EPiServer.Core;
using EPiServer.Research.Wiki;
using EPiServer;
using System.Collections.Generic;
using EPiServer.Research.Wiki.Core;
using EPiServer.Common.Tags;
using EPiServer.Common;
using System.Collections.Specialized;
using EPiServer.Templates.RelatePlus.Templates.PageEntity;
using EPiServer.Community;
using EPiServer.Templates.RelatePlus;

namespace Wiki.EPiServer.Research.Wiki.Core
{
    public partial class SaveArticleAjax : TemplatePage
    {

        [WebMethod]
        public static string CreateNewSection(string name, string type, string body, string comment, string pageid)
        {
           
            if (HasCreateAccess(pageid))
            {
                body = HttpUtility.UrlDecode(body);

                name = HttpUtility.UrlDecode(name);
               
                PageReference pr = PageReference.Parse(pageid); //Add below this
                PageReference newS = WikiManager.Instance.CreateNewSection(pr, name, type, body, comment, pr);
                return (DataFactory.Instance.GetPage(newS).LinkURL);
            }
            return "";
        }

        [WebMethod]
        public static string AddTags(string retVal, string pageid)
        {

            PageData page = new PageData();

            if (!string.IsNullOrEmpty(pageid))
            {
                page = WikiManager.Instance.GetWikiArticle(PageReference.Parse(pageid));

                TagCollection tags = new TagCollection();

                tags = ReadClientData(retVal);

                PageEntity pe = PageEntityHandler.GetPageEntityByGUID(page.PageGuid);

                if (pe == null)
                {
                    pe = (PageEntity)PageEntityHandler.AddPageEntity((PageEntity)Activator.CreateInstance(PageEntityUtils.GetPageEntityType(page), page.PageGuid, SiteHandler.CurrentSite));
     
                }
                    WikiArticlePageEntity wikiArticlePageEntityCloned = pe.Clone() as WikiArticlePageEntity;
                    if (wikiArticlePageEntityCloned != null)
                    {
                        wikiArticlePageEntityCloned.EntityTags.SelectiveAdd(tags, CommunitySystem.CurrentContext.DefaultSecurity.CurrentUser);
                        PageEntityHandler.UpdatePageEntity(wikiArticlePageEntityCloned);
                     
                        pe = null;
                    }
                
                
            }
            return "";
        }


        public static TagCollection ReadClientData(string tagslongstring)
        {
            string[] tags = tagslongstring.Split(',');

            TagCollection clientTagList = new TagCollection();

            foreach (string tag in tags)
            {
                if (String.IsNullOrEmpty(tag))
                {
                    continue;
                }

                string[] tagParts = tag.Split('|');

                int total;
                HybridDictionary tagsdic = new HybridDictionary(false);

                PredefinedTagCollection predefinedTags = TagHandler.GetPredefinedTags(null, SiteHandler.CurrentSite);
                foreach (var predefinedTag in predefinedTags)
                {
                    if (predefinedTag.Tag.Name.Contains(tagParts[1]))
                    {
                        tagsdic.Add(predefinedTag.Tag.ID, predefinedTag.Tag.Name);
                    }
                }

                TagCollection allTags = TagHandler.GetTags(null, SiteHandler.CurrentSite, 1, 500, out total);

                foreach (Tag t in allTags)
                {
                    if (t.Name.Contains(tagParts[1]) && !tagsdic.Contains(t.ID))
                    {
                        tagsdic.Add(t.ID, t.Name);
                    }
                }
                int tagID;

                if (!Int32.TryParse(tagParts[0], out tagID))
                {
                    //Invalid tag ID
                    continue;
                }

                // New tag
                if (tagsdic.Count == 0)
                {
                    string tagName = tagParts[1];

                    if (String.IsNullOrEmpty(tagName))
                    {
                        //Invalid tag name
                        continue;
                    }

                    Tag newTag = new Tag(tagName);
                    clientTagList.Add(TagHandler.AddTag(newTag));
                }
                else
                {
                    Tag existingTag = TagHandler.GetTag(tagID);

                    if (existingTag != null)
                    {
                        clientTagList.Add(existingTag);
                    }
                }
            }

            return clientTagList;
        }

        [WebMethod]
        public static string Cancel(string pageid)
        {
            EditManager.Instance.ReleaseLock(PageReference.Parse(pageid));
            return "";
        }

        public static string UrlEncode(string url)
        {
            return HttpUtility.UrlDecode(url).Replace(" ", "+");
        }

        [WebMethod]
        public static string CreateNewArticle(string name, string type, string body, string comment, string pageid, string showtoc, string selectedcats)
        {
           
            if (HasCreateAccess(pageid))
            {
                body = HttpUtility.UrlDecode(body);

                name = HttpUtility.UrlDecode(name);
                string urlname = UrlEncode(name);
                if (String.IsNullOrEmpty(showtoc))
                {
                    showtoc = "false";
                }
                else
                {

                    showtoc = "true";
                }
                int[] categories = GetSelectCats(selectedcats);

                PageReference pr = WikiManager.Instance.CreateNewArticle(new PageReference(pageid), name, body, comment, urlname, bool.Parse(showtoc), categories);

                return DataFactory.Instance.GetPage(pr).LinkURL;

            }

            return "";

        }

        private static int[] GetSelectCats(string selectedcats)
        {
            string[] tmp = selectedcats.Split(';');
            List<int> rt = new List<int>();

            foreach (string s in tmp)
            {
                if (!String.IsNullOrEmpty(s))
                    rt.Add(int.Parse(s));
            }
            return rt.ToArray();
        }

        public static bool HasCreateAccess(string pageid)
        {
            return DataFactory.Instance.GetPage(new PageReference(pageid)).QueryDistinctAccess(global::EPiServer.Security.AccessLevel.Create);
        }

        [WebMethod]
        public static string UpdateArticle(string name, string type, string body, string comment, string pageid, string showtoc, string selectedcats, string IsArticle)
        {
         
            if (String.IsNullOrEmpty(showtoc))
            {
                showtoc = "false";
            }
            if (HasCreateAccess(pageid))
            {
                body = HttpUtility.UrlDecode(body);

                name = HttpUtility.UrlDecode(name);
               
                PageReference pr = PageReference.Parse(pageid);
                //Edited article or section
                if (bool.Parse(IsArticle))
                {
                    WikiManager.Instance.UpdateArticle(pr, name, body, comment, bool.Parse(showtoc), GetSelectCats(selectedcats));
                }
                else
                {
                    WikiManager.Instance.UpdateSection(pr, name, type, body, comment);
                }
                EditManager.Instance.ReleaseLock(pr);
                return DataFactory.Instance.GetPage(pr).LinkURL;

            }

            return "";
        }
    }
}
